<template>
  <el-container>
    <el-header>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>基础管理</el-breadcrumb-item>
        <el-breadcrumb-item>爱心捐赠</el-breadcrumb-item>
      </el-breadcrumb>
    </el-header>
    <el-main>
      <div class="products-display">
        <div v-for="product in products" :key="product.id" class="product">
          <div class="product-image">
            <img :src="'http://192.168.1.19:8077/share/hope/common/view-avatar?path='+product.imageUrl"
                 :alt="product.name">
          </div>
          <div class="product-info">
            <h1>{{ product.name }}</h1>
            <p>{{ product.description }}</p>
            <p>爱心积分: {{ product.price }}</p>
            <el-button type="primary" @click="exchange(product)" size="mini">兑换</el-button>
            <!--        <el-button type="primary" @click="addToCart(product)" size="mini">加购</el-button>-->
          </div>
        </div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[9, 12, 15, 18]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
        <!--    兑换商品-->
        <el-dialog :visible.sync="dialogVisible" title="选择帮助对象">
          <el-form>
            <el-form-item label="收件人姓名">
              <el-select v-model="selectChild.id" filterable placeholder="请选择" @change="getChildById()">
                <el-option
                  v-for="item in childList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              仅看收藏列表
              <el-switch
                v-model="collect"
                @change="switchChange"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
            <el-form-item label="详细地址">
              <el-input v-model="selectChild.address"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="sendPackage(selectChild.id)">发 送</el-button>
          </div>
        </el-dialog>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import {regionData, CodeToText} from 'element-china-area-data'
import user from "../system/user.vue";

export default {
  data() {
    return {
      collect:true,
      options: regionData,
      selectedOptions: [],
      addtions: {},			//存储地址数据
      dialogVisible: false,
      receiverName: '',
      receiverPhone: '',
      receiverAddress: '',
      pageSize: 9,
      currentPage: 1,
      total: 0,
      products: [],
      user: {},
      childList: [],
      selectChild: {
        name: '',
        address: ''
      },
      selectProductId:0
    }
  },

  created() {
    this.user = JSON.parse(localStorage.getItem('userInfo'))
    this.getProducts()
  },
  methods: {
    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.getProducts()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getProducts()
    },
    getProducts() {
      const request = {
        page: {
          desc: "",
          size: this.pageSize,
          asc: "",
          current: this.currentPage
        },
        query: {}
      }
      this.$axios.post('/products/page', request).then(res => {
        if (res.data.code === 20000) { //成功
          this.products = res.data.data.records
          this.total = res.data.data.total
        } else { //失败
          this.$message.error(res.data.msg)
        }
      });
    },

    exchange(product) {
      if (this.user.loveCoin < product.price) {
        this.$message.error("很抱歉，您的爱心币不够呢！")
        return
      }
      this.dialogVisible = true
      this.selectProductId=product.id
      this.getAllChildren(this.user.id)

    },
    switchChange(e){
      this.collect=e
      this.getAllChildren(this.user.id)
    },
    getAllChildren(userId) {
      let url = "pool_child/get_all";
      if (this.collect){
        url +="?userId=" + userId
      }
      this.$axios.get(url).then(res => {
        if (res.data.code === 20000) { //成功

          let option = res.data.data
          this.childList = option.map((item, index) => {
            return Object.assign({}, {'value': item.id, 'label': item.name})
          })
          // console.log(this.childList)
        } else { //失败
          this.$message.error(res.data.msg)
        }
      })
    },
    getChildById() {
      // console.log(this.selectChild.id)
      this.$axios.get(`pool_child/by_id?id=${this.selectChild.id}`).then(res => {
        if (res.data.code === 20000) { //成功

          this.selectChild=res.data.data
        } else { //失败
          this.$message.error(res.data.msg)
        }
      })
    },
    sendPackage(id) {
      if (id===undefined){
        this.$message.error('请选择你要帮助的人')
        return
      }
      this.$axios.get(`products/exchange?userId=${this.user.id}&productId=${this.selectProductId}`).then(res => {
        if (res.data.code === 20000) { //成功
          this.$message.success(res.data.msg)
          this.refreshLocalStorage(this.user)
        } else { //失败
          this.$message.error(res.data.msg)
        }
      })
      this.dialogVisible = false
    },
    refreshLocalStorage(user){
      const request = {
        accountNumber: user.accountNumber,
        password: user.password
      }
      this.$axios.post('user/login', request).then(res => {
        if (res.data.code === 20000) { //成功
          // this.$message.success(res.data.msg)
          localStorage.setItem("userInfo", JSON.stringify(res.data.data));
          location.reload()
        } else { //失败
          this.$message.error(res.data.msg)
        }
      });
    }
  }
};
</script>

<style>
.products-display {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  /*margin:  0;*/
}

.product {
  flex-basis: 30%;
  margin-bottom: 20px;
  margin-top: 20px;
}

.product-image img {
  max-width: 100%;
  max-height: 200px;
  object-fit: contain;
}


</style>
